/**
 * @Project Name:blog-business-service
 * @Package Name:cn.hoofungson.blog.business.service.provider.service.article
 * @Since JDK 1.8
 */

package cn.hoofungson.blog.business.service.provider.service.article;

import cn.hoofungson.blog.business.service.interfaces.domain.dto.article.ArticleDTO;
import cn.hoofungson.blog.business.service.provider.converter.article.ArticleConverter;
import cn.hoofungson.blog.business.service.provider.model.entity.article.ArticlePO;
import cn.hoofungson.blog.business.service.provider.repositories.article.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Description: ArticleService
 * @Author 胡松 hoofungson@163.com
 * @Date 2020-03-25 8:30
 * @Version V1.0
 */
@Service
public class ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    /**
     * 保存或更新
     *
     * @param articleDTO
     **/
    public void save(ArticleDTO articleDTO) {
        if (null == articleDTO) {
            return;
        }
        ArticlePO articlePO = new ArticlePO();
        ArticleConverter.convert(articleDTO, articlePO);
        this.articleRepository.save(articlePO);
    }

    /**
     * 根据ID删除
     *
     * @param id
     **/
    public void deleteById(Long id) {
        this.articleRepository.deleteById(id);
    }

    /**
     * 根据所传实体删除
     *
     * @param articleDTO
     **/
    public void delete(ArticleDTO articleDTO) {
        if (null == articleDTO) {
            return;
        }
        ArticlePO articlePO = new ArticlePO();
        ArticleConverter.convert(articleDTO, articlePO);
        this.articleRepository.delete(articlePO);
    }

    /**
     * 删除所有
     **/
    public void deleteAll() {
        this.articleRepository.deleteAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     **/
    public ArticleDTO get(Long id) {
        Optional<ArticlePO> optional = this.articleRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        ArticlePO articlePO = optional.get();
        ArticleDTO articleDTO = new ArticleDTO();
        ArticleConverter.convert(articlePO, articleDTO);
        return articleDTO;
    }
}
